package edu.towson.cosc671.jdehlingerstutterwebapp.server;

import edu.towson.cosc671.jdehlingerstutterwebapp.client.GreetingService;
import edu.towson.cosc671.jdehlingerstutterwebapp.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	public String greetServer(String input) throws IllegalArgumentException {
		// Verify that the input is valid. 
		if (!FieldVerifier.isValidText(input)) {
			// If the input is not valid, throw an IllegalArgumentException back to
			// the client.
			throw new IllegalArgumentException(
					"Your text must be at least 10 characters long");
		}	
		
		return checkStutter(input);
	}
	
	private String checkStutter (String input)
	   {
	      int    lineNum  = 0;
		  String output	  = "";
	      String line     = null;
	      String lastWord = null;
	      String newline = " <br> ";

	      String[] lines = input.split ("\n");
	      
	      line = lines[lineNum];
	      lineNum++;
	    	  
		  while (line != null)
		  {
		  	 // Remove all non alpha-numeric characters
		     // This replaces the IsDelimit() function in the C version.
		     line = line.replaceAll("[^a-zA-Z0-9 ]", "");
		     line = line.toLowerCase();
	
		     // Splits the line into words and puts in an array of strings
		     String[] words = line.split(" ");
	
		     // Compare with the last word on the previous line
		     if (words[0].equals(lastWord))
		        output = output + "Repeated word at line number " + lineNum + ": " + words[0] + newline;	        
	
		     // Stop before the end, nothing to compare the last word with
		     for (int i = 0; i < (words.length-1); i++)
		     {
		        // Check to see if the current and subsequent words are the same
		   	    if (words [i].equals (words [i+1]))
		        {
		    		 output = output + "Repeated word at line number " + lineNum + ": " + words[i] + newline;
		        }
		     }
		     // Save last word in the line
		     lastWord = words [words.length-1];
		     lineNum++;
		     
		     if (lineNum  <= lines.length)
		       	 line = lines[lineNum-1];		    	 	
		     else
		    	 line = null;		     
		  }
	   	  
		  if (output.equalsIgnoreCase(""))
			  output = "No repeated words found.";
		  return output;
	   }	
}
